"""
@Author    : ghenyar
@Time      : 2025/8/28 12:34
@File      : comm_func
@Desc      :
"""

import ast
import json

from fastapi import Request, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.common.exception.exceptions import NotFoundException
from app.common.model_querier import ModelQuerier
from app.core.db import async_get_db
from app.libs.oss_file import StorageFile
from app.models.configs_model import ConfigsModel
from app.utils.files import FileUtils
from app.utils.redisCache import RedisCache


async def get_file(request: Request, db: AsyncSession = Depends(async_get_db)):
    """
    文件预览
    :param request: 请求体
    :param db: 数据库会话
    :return: 文件流
    """
    file_name = request.path_params['file_name']
    result = await FileUtils.download(file_name, request)
    if result is None:
        # 远程文件
        range_header = request.headers.get('range')
        store_config = await get_store_config(db)
        storage = StorageFile(store_config, range_header)
        stream = storage.download_stream(file_name)
        if not stream:
            raise NotFoundException("未找到相应的文件")
        return stream
    return result


async def get_store_config(db: AsyncSession):
    """
    获取存储配置（带 Redis 缓存）
    :return: 存储配置字典 or None
    """
    config_key = "storage_config"
    redis = RedisCache()
    # 尝试从Redis中获取配置
    if await redis.has(config_key):
        config_value = await redis.get(config_key)
    else:
        # 从数据库中获取启用的存储配置
        config = await ModelQuerier(db, ConfigsModel).where(ConfigsModel.types == "storage",
                                                        ConfigsModel.enable == True).get_one()
        if config:
            config_value = ast.literal_eval(config.value) if config.value else {}
            # 构建返回的字典
            config_value = {"types": config.key, **config_value}
            # 将字典转换为JSON字符串存储到Redis中
            await redis.set(config_key, json.dumps(config_value))
        else:
            return None

    return config_value


async def get_config(db: AsyncSession, type_name: str, key: str):
    """
    获取系统配置
    :param db: 数据库会话
    :param type_name: 配置类型
    :param key: 配置键
    :return:
    """
    if not key:
        key = type_name
    config_key = f"{type_name}_{key}"

    # 尝试从Redis中获取配置
    redis_cache = RedisCache()
    if await redis_cache.has(config_key):
        config_value = await redis_cache.get(config_key)
    else:
        # 从数据库中获取配置
        config = await ModelQuerier(db, ConfigsModel).where(ConfigsModel.types == type_name,
                                                        ConfigsModel.key == key,
                                                        ConfigsModel.enable == True).get_one()
        if config:
            config_value = ast.literal_eval(config.value) if config.value else {}
            # if type_name == "storage" or type_name == "auth_zone":
            #     config_value = {
            #         "enable":int(config.enable),
            #         "value":config_value,
            #         "key":config.key,
            #     }
            # 存储到Redis中
            await redis_cache.set(config_key, config_value)
        else:
            config_value = {}
    # # 检查配置是否存在或已启用
    # if not config_value or (type_name != "storage" and config_value.get("enable") == 0):
    #     return None

    return config_value
